﻿using System;
using Volo.Abp.Validation.StringValues;

namespace Xms.Abp.Validation.StringValues;

[Serializable]
[ValueValidator("DECIMAL")]
public class DecimalValueValidator : ValueValidatorBase
{
    public decimal MinValue
    {
        get => (this["MinValue"] ?? "0").To<decimal>();
        set => this["MinValue"] = value;
    }

    public decimal MaxValue
    {
        get => (this["MaxValue"] ?? "0").To<decimal>();
        set => this["MaxValue"] = value;
    }

    public DecimalValueValidator()
    {
        MinValue = decimal.MinValue;
        MaxValue = decimal.MaxValue;
    }

    public DecimalValueValidator(decimal minValue = decimal.MinValue, decimal maxValue = decimal.MaxValue)
    {
        MinValue = minValue;
        MaxValue = maxValue;
    }

    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return false;
        }

        if (value is decimal val)
        {
            return IsValidInternal(val);
        }

        if (value is string)
        {
            if (decimal.TryParse(value as string, out var longValue))
            {
                return IsValidInternal(longValue);
            }
        }

        return false;
    }

    protected virtual bool IsValidInternal(decimal value)
    {
        return value.IsBetween(MinValue, MaxValue);
    }
}
